<template>
  <div ref="editorRef" class="editor-main"></div>
</template>

<script lang="ts" setup>
import { basicSetup, EditorView } from "codemirror";
import { EditorState } from "@codemirror/state";
import { javascript } from "@codemirror/lang-javascript";
import { onMounted, ref, watch } from "vue";
const emit = defineEmits(["update:modelValue"]);
let props = defineProps({
  modelValue: {
    type: String,
    required: false,
    default: ""
  }
});
const editorRef = ref();
const editorView = ref();
const initEditor = () => {
  const startState = EditorState.create({
    doc: "",
    extensions: [
      basicSetup,
      javascript(),
      EditorView.updateListener.of(function (e) {
        if (e.docChanged) {
          emit("update:modelValue", e.state.doc.toString());
        }
      })
    ]
  });
  if (editorRef.value) {
    editorView.value = new EditorView({
      state: startState,
      parent: editorRef.value
    });
  }
};
// watch(
//   () => props.value,
//   (data) => {
//     if (data && data.message !== undefined) {
//       const message = `[${data.level}] ${stringFormat(data.message, data.variables)}` + "\n";
//       editorView.value.dispatch({
//         changes: {
//           from: editorView.value.state.doc.length,
//           to: editorView.value.state.doc.length,
//           insert: message
//         }
//       });
//     }
//   }
// );
watch(
  () => props.modelValue,
  (New) => {
    if (New !== editorView.value.state.doc.toString()) {
      editorView.value.dispatch({
        changes: {
          from: 0,
          to: editorView.value.state.doc.length,
          insert: New
        }
      });
    }
  }
);
// onMounted生命周期可以保证读取到dom元素
onMounted(() => {
  initEditor();
});
</script>

<style lang="scss" scoped>
.editor-main {
  width: 100%;
  height: 100%;
  overflow: auto;
}
</style>
